<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产名称" prop="assetsName" >
        <el-input
            style="width: 200px"
            v-model="queryParams.assetsName"
            placeholder="请输入资产名称查询"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产编号" prop="assetsNo">
        <el-input
            style="width: 200px"
            v-model="queryParams.assetsNo"
            placeholder="请输入资产编号查询"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName" v-hasRole="['admin']">
        <el-input
            style="width: 200px"
            v-model="queryParams.userName"
            placeholder="请输入用户名称查询"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="showOperationColumn">
<!--      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['receive:receive:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['receive:receive:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['receive:receive:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['receive:receive:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiveList" @selection-change="handleSelectionChange">
      <!--    <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="每条记录的唯一标识符" align="center" prop="id" />-->
      <el-table-column label="资产名称" align="center" prop="assetsName" width="200"/>
      <el-table-column label="资产编号" align="center" prop="assetsNo" />
      <el-table-column label="用户名称" align="left" prop="userName" width="100"/>
      <el-table-column label="领用日期" align="center" prop="date" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="可还日期" align="center" prop="returnDate" width="150">
        <template #default="scope">
          <strong style="color: #C03639" v-if="scope.row.status===`1` &&(new Date(scope.row.returnDate).getDate() < new Date().getDate())">
            {{ parseTime(scope.row.returnDate, '{y}-{m}-{d}') }}
          </strong>
          <span v-else>{{ parseTime(scope.row.returnDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
<!--          <dict-tag :options="assets_review_status" :value="scope.row.status"/>-->
          <el-tag type="warning" size="small" effect="dark" v-if="scope.row.status===`0`">待审核</el-tag>
          <el-tag type="primary" size="small" effect="dark" v-if="scope.row.status===`1`">通过</el-tag>
          <el-tag type="danger" size="small" effect="dark" v-if="scope.row.status===`2`">拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="归还状态" align="center" prop="returnStatus">
        <template #default="scope">
<!--          <dict-tag :options="assets_return_status" :value="scope.row.returnStatus"/>-->
          <el-tag size="small" type="info" effect="dark" v-if="scope.row.returnStatus===`0`&&scope.row.status===`1`">未归还</el-tag>
          <span size="small" type="info" effect="dark" v-else></span>
          <el-tag size="small" type="success" effect="dark" v-if="scope.row.returnStatus===`1`">已归还</el-tag>
          <el-tag size="small" type="danger" effect="dark" v-if="scope.row.returnStatus===`2`">逾期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="comment" width="200px" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px" >
        <template #default="scope">
          <el-button link type="primary"  v-if="scope.row.status===`0`" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['receive:receive:edit']">修改</el-button>
          <el-button link type="primary"  v-hasRole="['admin']" v-if="scope.row.returnStatus===''||scope.row.returnStatus!==`0`" icon="Edit"
                     v-hasPermi="['receive:receive:edit']" @click="changeReviewReturnStatus(scope.row,`未归还`)">撤回已归还</el-button>
          <el-button link type="primary" v-if="scope.row.status===`0`" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['receive:receive:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核领用" v-hasRole="['admin']" align="center" class-name="small-padding fixed-width" fixed="right" width="150px" >
        <template #default="scope">
          <el-tag link type="primary" style="cursor: pointer" effect="dark" v-if="scope.row.status===`0`" @click="changeReviewStatus(scope.row,`通过`)">通过</el-tag>
          <el-tag link  type="danger"  style="cursor: pointer;margin-left: 3px" effect="dark" v-if="scope.row.status===`0`"  @click="changeReviewStatus(scope.row,`拒绝`)" >拒绝</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改资产领用明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="receiveRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资产名称" prop="assetsName">
          <el-select style="width: 100%" v-model="form.assetsId"  @change="updateSelectedAsset">
            <el-option v-for="item in assetsList" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产编号" prop="assetsNo">
          <el-input v-model="form.assetsNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-select style="width: 100%" v-model="form.userId" disabled>
            <el-option v-for="item in receiveList" :key="item.id" :value="item.userId" :label="item.userName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领用日期" prop="date">
          <el-date-picker clearable
                          v-model="form.date"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择领用日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="可还日期" prop="returnDate">
          <el-date-picker clearable
                          v-model="form.returnDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择归还日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="归还状态" prop="returnStatus" v-hasRole="['admin']">
          <el-select v-model="form.returnStatus" placeholder="请选择归还状态" style="width: 100%;">
            <el-option
                v-for="dict in assets_return_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" rows="3" v-model="form.comment" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Receive">
import { listReceive, getReceive, delReceive, addReceive, updateReceive } from "@/api/receive/receive";
import { listAssets } from "@/api/assets/assets";
import useUserStore from "@/store/modules/user.js";
import {ElMessageBox} from "element-plus";
const store = useUserStore();


const { proxy } = getCurrentInstance();
const { assets_review_status, assets_return_status } = proxy.useDict('assets_review_status', 'assets_return_status');

const receiveList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const assetsList = ref([]);
const userNameList = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const title = ref("");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    assetsName: null,
    assetsNo: null,
    userName: null,
  },
  rules: {
    assetsId: [
      { required: true, message: "资产不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户不能为空", trigger: "blur" }
    ],
    date: [
      { required: true, message: "领用日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);



/*判断是否拥有权限*/
// 假设你已经从 Vuex 或其他地方获取了权限列表
const permissions = computed(() => {
  // 从 Vuex store 获取权限列表
  return useUserStore().permissions;
});

// 计算属性，检查是否显示操作列
const showOperationColumn = computed(() => {
  return permissions.value.includes('receive:receive:edit') ||
      permissions.value.includes('receive:receive:remove')||
      permissions.value.includes('receive:receive:export');
});
function changeReviewStatus(row, status) {
  // 使用对象展开运算符进行深拷贝，更简洁且易于理解
  const formCopy = { ...row };

  // 设置 status 数值
  const statusMap = { '通过': 1, '拒绝': 2 };
  formCopy.status = statusMap[status] || null;

  ElMessageBox.confirm(`您确定${status}吗？`, '确认审核', {type: "warning"})
      .then(() => {
        return updateReceive(formCopy);
      })
      .then(() => {
        proxy.$modal.msgSuccess("审核成功");
        //open.value = false;
        getList();
      })
      .catch(error => {
        proxy.$modal.msgError("审核失败");
        // 可以在这里添加错误提示给用户
      });
}
function changeReviewReturnStatus(row, returnStatus) {
  // 使用对象展开运算符进行深拷贝，更简洁且易于理解
  const formCopy = { ...row };

  // 设置 status 数值
  const statusMap = { '未归还': `0`, '已归还': `1` };
  formCopy.returnStatus = statusMap[returnStatus] || null;
  console.log("formCopy.returnStatus=",formCopy.returnStatus)

  ElMessageBox.confirm(`您确定变更该物资为未归还吗？`, '确认审核', {type: "warning"})
      .then(() => {
        return updateReceive(formCopy);
      })
      .then(() => {
        proxy.$modal.msgSuccess("已成功变更该物资归还状态");
        //open.value = false;
        getList();
      })
      .catch(error => {
        proxy.$modal.msgError("变更该物资归还状态失败了");
        // 可以在这里添加错误提示给用户
      });
}
/** 查询资产领用明细列表 */
function getList() {
  loading.value = true;
  listReceive(queryParams.value).then(response => {
    receiveList.value = response.rows;
    console.log("receiveList",response.rows)
    total.value = response.total;
    loading.value = false;
  });
}
// 查询各种集合：资产集合、员工集合
function getAllList() {
  loading.value = true;
/*  listUser(null).then(response => {
    userNameList.value = response.rows;
    loading.value = false;
  });*/

  listAssets(null).then(response => {
    assetsList.value = response.rows;
    loading.value = false;
  });

}

/*因为asset.id对应的是assetReceive.asssetsId,id不能同步，因此需要指定监视*/
const updateSelectedAsset = () => {
  const selectedAsset = assetsList.value.find(item => item.id === form.value.assetsId);
  if (selectedAsset) {
    form.value.assetsNo = selectedAsset.no;
  } else {
    form.value.assetsNo = ''; // 如果未找到匹配项，清空资产编号
  }
};
watch(() => form.value.assetsId, updateSelectedAsset);

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    assetsId: null,
    userId: null,
    date: null,
    comment: null,
    returnDate: null,
    status: null,
    returnStatus: null
  };
  proxy.resetForm("receiveRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资产领用明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReceive(_id).then(response => {
    form.value = response.data;
    if (form.value.status === `1`){
      proxy.$modal.msgError("审核已通过，不能修改");
      return;
    }
    open.value = true;
    title.value = "修改资产领用明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["receiveRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReceive(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReceive(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _id = row.id || ids.value
  getReceive(_id).then(response => {
    form.value = response.data;
    if (form.value.status === `1`){
      proxy.$modal.msgError("审核已通过，不能删除");
      return;
    }});
  // const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资产领用明细编号为"' + _ids + '"的数据项？').then(function() {
    return delReceive(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('receive/receive/export', {
    ...queryParams.value
  }, `receive_${new Date().getTime()}.xlsx`)
}

getList();
getAllList();
</script>